package com.ztz.mynewdemo.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.ztz.mynewdemo.R;
import com.ztz.mynewdemo.Service.UpdateService;
import com.ztz.mynewdemo.adapter.WeatherAdapter;
import com.ztz.mynewdemo.bean.WeatherResponse;
import com.ztz.mynewdemo.utils.HttpUtil;
import com.ztz.mynewdemo.utils.NewsApi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;


public class WeatherActivityTwo extends BaseActivity {
    @BindView(R.id.title_city)
    TextView titleCity;
    @BindView(R.id.title_update_time)
    TextView titleUpdateTime;
    @BindView(R.id.degree_text)
    TextView degreeText;
    @BindView(R.id.weather_info_text)
    TextView weatherInfoText;
    @BindView(R.id.comfort_text)
    TextView comfortText;
    @BindView(R.id.car_wash_text)
    TextView carWashText;
    @BindView(R.id.sport_text)
    TextView sportText;
    @BindView(R.id.advice)
    TextView advice;
    @BindView(R.id.text_wind)
    TextView textWind;
    @BindView(R.id.text_comfort)
    TextView textComfort;
    @BindView(R.id.weather_layout)
    ScrollView weatherLayout;
    @BindView(R.id.nav_btn)
    Button navBtn;
    @BindView(R.id.rl_weather)
    RecyclerView rlWeather;
    @BindView(R.id.swipe_weather)
    SwipeRefreshLayout swipeWeather;
    private ImageView iv_Bing;
    private static final String TAG = "WeatherActivityTwo";
    List<WeatherResponse.ResultBean.TodayBean> todayBeanList = new ArrayList<>();
    List<WeatherResponse.ResultBean.FutureBean> futureBeanList = new ArrayList<>();
    WeatherAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_weather_two);
        ButterKnife.bind(this);
        iv_Bing = (ImageView) findViewById(R.id.iv_bing);
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        String bingPic = pref.getString("bing_pic", null);
        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(iv_Bing);
        } else {
            loadImage();
        }
        final double longitude = getIntent().getDoubleExtra(LocateActivity.LONGITUDE, 0);
        final double latitude = getIntent().getDoubleExtra(LocateActivity.LATITUDE, 0);
        Intent intentService = new Intent(WeatherActivityTwo.this, UpdateService.class);
        startService(intentService);
        rlWeather.setLayoutManager(new LinearLayoutManager(this));
        adapter = new WeatherAdapter(this, futureBeanList, R.layout.weather_item);
        rlWeather.setHasFixedSize(true);
        rlWeather.setNestedScrollingEnabled(false);
        rlWeather.setAdapter(adapter);
        swipeWeather.setColorSchemeResources(R.color.colorPrimary);
        swipeWeather.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                futureBeanList.clear();
                getData(latitude, longitude);
            }
        });
        getData(latitude, longitude);
    }

    private void getData(double latitude, double longitude) {
        OkGo.<String>get(NewsApi.GEO)
                .tag(this)
                .params("lon", longitude)
                .params("lat", latitude)
                .params("format", 2)
                .params("dtype", "json")
                .params("key", "60f7fc28a4b0e9e8816813b2db7ed5f0")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String s = response.body();
                        Gson gson = new Gson();
                        final WeatherResponse weatherResponse = gson.fromJson(s, WeatherResponse.class);
                        todayBeanList.add(weatherResponse.getResult().getToday());
                        futureBeanList.addAll(weatherResponse.getResult().getFuture());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                titleCity.setText(todayBeanList.get(0).getCity());
                                degreeText.setText(todayBeanList.get(0).getTemperature());
                                weatherInfoText.setText(todayBeanList.get(0).getWeather());
                                textWind.setText(todayBeanList.get(0).getWind());
                                textComfort.setText(todayBeanList.get(0).getDressing_index());
                                advice.setText(todayBeanList.get(0).getDressing_advice());
                                comfortText.setText("洗车指数:" + todayBeanList.get(0).getWash_index());
                                carWashText.setText("旅行指数:" + todayBeanList.get(0).getTravel_index());
                                sportText.setText("运动建议:" + todayBeanList.get(0).getExercise_index());
                                adapter.notifyDataSetChanged();
                                swipeWeather.setRefreshing(false);
                            }
                        });
                        Log.i(TAG, "onSuccess: " + s);
                    }
                });
    }

    private void loadImage() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                final String bingPic = response.body().string();
                Log.i(TAG, "onResponse: " + bingPic);
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivityTwo.this).edit();
                editor.putString("bing_Pic", bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivityTwo.this).load(bingPic).into(iv_Bing);
                    }
                });
            }
        });
    }

    @OnClick(R.id.nav_btn)
    public void onViewClicked() {
        finish();
    }
}
